--[[

客户端网络模块	

--]]

require("Scripts/Common/Utility")
require("Scripts/Common/Class")
require("Scripts/Common/Json")

NetSystem = Class()

function NetSystem:Ctor()
	-- 客户端连接服务端成功的回调函数
	self._connect_succeed = nil
	-- 客户端连接服务端失败的回调函数
	self._connect_failed = nil
end

-- 注册回调函数
function NetSystem:RegisterCallBack(succeed_func, failed_func)
	self._connect_succeed = succeed_func
	self._connect_failed = failed_func
end

-- 客户端调用服务端函数
function NetSystem:SendCall(method, ...)
	-- 将arg字符串通过协议发送出去
	Global_NetSystem:SendJsonCall(method, Json.encode(arg))
end

-- 连接服务端
function NetSystem:Connect(ip, port)
	Global_NetSystem:Connect(ip, port)
end

-- 向服务端发送脚本代码
function NetSystem:SendRunScript(script)
	Global_NetSystem:SendRunScript(script)
end

g_NetSystem = NetSystem()

-- 客户端连接服务端，成功
function Global_Client_Connect_Succeed()
	-- Sail_Log("sail connect succeed")
	local func = g_ClientNetSystem._connect_succeed
	if func then func() end
end

-- 断开连接
function Global_Client_Disconnect()
end

-- 客户端链接服务端，失败
function Global_Client_Connect_Failed()
	-- Sail_Log("sail connect failed")
	local func = g_ClientNetSystem._connect_failed
	if func then func() end
end

-- 服务端调用客户端函数
function Global_Client_JsonInvoke(method, json_arg)
	-- json_arg 为参数字符串，decode后为一个参数数组
	json_arg = Json.decode(json_arg)
	-- 查找全局函数method，并将arg展开作为函数的参数调用
	_G[method](unpack(json_arg))
end
